import React, { Component } from 'react';
import { Button, Spin, Input, Table, Modal, Pagination, Space } from 'antd';
import { message } from 'antd';
import {
    getCrmByParam,
    getCrmFields,
    getCrmProductsByParam,
    getCrmRecordFromSql,
    intIfNull,
    isBlank
} from "../util/util";
import { API_URL } from "../constants";
import moment from "moment";
import { SearchOutlined } from "@ant-design/icons";


const ZOHO = window.ZOHO;

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            user: {},
            loading: false,
            modalVisible: false,
            screenHeight: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
            selectedContractRowKeys: [],
            contractColumns: [{
                title: '外销合同号',
                dataIndex: 'Subject',
                key: 'Subject',
                type: 'text',
                ...this.getColumnSearchProps('Subject'),

            }, {
                title: '客户简称',
                dataIndex: 'customername',
                key: 'customername',
                type: 'text',
                ...this.getColumnSearchProps('Account_Name'),

            }, {
                title: '客户订单号',
                dataIndex: 'AccountOrderNo',
                key: 'AccountOrderNo',
                type: 'text',
                ...this.getColumnSearchProps('AccountOrderNo'),

            },],
            contactData: [],
            column: [{
                title: '商品库编码',
                dataIndex: 'Product',
                key: 'Product',
            }, {
                title: '内部代码',
                dataIndex: 'internalcode',
                key: 'internalcode',
            }, {
                title: '合同号',
                dataIndex: 'Subject',
                key: 'Subject',
            }, {
                title: '客户订单号',
                dataIndex: 'AccountOrderNo',
                key: 'AccountOrderNo',
            }, {
                title: '数量',
                dataIndex: 'Quantity',
                key: 'Quantity',
            },],
            dataSource: [],
            selectedRowKeys: [],
            searchInput: [],
        };
    }

    async componentDidMount() {
        this.setState({ loading: true })
        let user = {};
        ZOHO.CRM.UI.Resize({ height: "2000", width: "2000" }).then(function (data) {
            console.log(data);
        });
        await ZOHO.CRM.CONFIG.getCurrentUser().then(function (data) {
            user = data.users[0]
        });

        let selectedRowKeys = [];
        let selectedContractRowKeys = [];
        let dataSource = [];
        if (!isBlank(window.data)) {
            let data = window.data
            console.log(data)
            if (isBlank(data.Account)) {
                Modal.error({
                    title: '请先选择客户',
                    content: '请先选择客户',
                    okText: '确定',
                    onOk: () => {
                        ZOHO.CRM.UI.Popup.close().then(() => {

                        });
                    }
                });
                return
            }
            if (isBlank(data.ShipperInformation)) {
                Modal.error({
                    title: '请先选择发货人',
                    content: '请先选择发货人',
                    okText: '确定',
                    onOk: () => {
                        ZOHO.CRM.UI.Popup.close().then(() => {

                        });
                    }
                });
                return
            }
            if (!isBlank(data.id1)) {
                selectedContractRowKeys = data.id1.split(",")
            }
            selectedRowKeys = data.LinkingModule8?.map(item => {
                return item.id1;
            })
            console.log(selectedRowKeys)
            console.log(selectedContractRowKeys)
            if (selectedContractRowKeys.length > 0) {
                dataSource = await getCrmRecordFromSql(`select 
        Parent_Id.Subject as Subject,Product_Name.id as productid,Product_Name.Product_Name as Product,id,internalcode
        ,Quantity,Parent_Id.AccountOrderNo as AccountOrderNo , Parent_Id.CountryCode as CountryCode,AccountprtNoAccountprtNo,Chinesespecification,Chptrequirements_material,Chineseingredients,
        Brand,Englishname,Specification,Nuofboxesinpg,Nuofboxeinnerbox,Lengthofouterbox,Heightofouterbox,Grossweight,NumberofCartons,
        Cartonwidth,Netweight,Volume,ABQuantity,List_Price,Productname,Packagingquantityperpg,Category,Parent_Id,Parent_Id.ContractDate as ContractDate,
        Parent_Id.Terms_and_Conditions as Terms_and_Conditions,Parent_Id.Currency as Currency,
        Unit,Packaginunit from Ordered_Items where Parent_Id in (${selectedContractRowKeys}) and ABQuantity>0 order by id desc`);
                console.log(dataSource)
            }

        }
        let fields = ['Subject', 'DeliveryDate', 'ContractDate', 'PayMethod', 'AccountOrderNo', 'ContractItem',
            'Quote_Name', 'Header', 'ContractType', 'TransactionMethod', 'ShipperInformationName', 'OverShort_Shipment',
            'Account_Name', 'Account_Name.Account_Name as customername', 'EstimatedShippingDate', 'Deal_Name', 'Currency', 'Account', 'Modified_By',
            'ShippingPort', 'Buttonchange', 'DestinationPort', 'Created_Time', 'Modified_Time', 'Created_By', 'Owner',
            'Terms_and_Conditions', 'Post_Contractual_Terms', 'Description', 'Sub_Total', 'Discount', 'Tax', 'Adjustment',
            'Grand_Total', 'SumABQuantity', 'Header.Name as Headername'];
        await getCrmRecordFromSql(`select ${fields} from Sales_Orders where (SumABQuantity>0 and Owner.id = ${user.id}) and Account_Name = ${window.data.Account.id} order by id desc`).then(data => {
            console.log(data)
            this.setState({ modalVisible: true, contactData: data })
        })
        console.log(user)
        this.setState({
            user: user,
            selectedRowKeys: selectedRowKeys,
            selectedContractRowKeys: selectedContractRowKeys,
            dataSource: dataSource,
            loading: false
        });
    }

    handleSave = async () => {
        this.setState({ loading: true });
        const { selectedRowKeys, dataSource } = this.state
        const LinkingModule8 = [];
        let selectData = [];
        dataSource.forEach(item => {
            if (selectedRowKeys.includes(item.id)) {
                selectData.push(item)
                LinkingModule8.push({
                    AccountOrderNo: item.AccountOrderNo,
                    Product: {
                        id: item.productid,
                        name: item.Product
                    },
                    AccountprtNo: item.AccountprtNo,
                    internalcode: item.internalcode,
                    Productname: item.Productname,
                    Chinesespecification: item.Chinesespecification,
                    Chptrequirements_material: item.Chptrequirements_material,
                    Chineseingredients: item.Chineseingredients,
                    Make: item.Brand,
                    Englishname: item.Englishname,
                    Specification: item.Specification,
                    Nuofboxesinpg: item.Nuofboxesinpg,
                    Nuofboxeinnerbox: item.Nuofboxeinnerbox,
                    Lengthofouterbox: item.Lengthofouterbox,
                    Heightofouterbox: item.Heightofouterbox,
                    Grossweight: item.Grossweight,
                    NumberofCartons: item.NumberofCartons,
                    Cartonwidth: item.Cartonwidth,
                    Netweight: item.Netweight,
                    Volume: item.Volume,
                    Purchaseunitprice: item.List_Price,
                    PurchaseQty: item.ABQuantity,
                    Packagingquantityperpg: item.Packagingquantityperpg,
                    Category: item.Category,
                    id1: item.id,
                    Unit: item.Unit,
                    Packaginunit: item.Packaginunit
                })
            }
        });

        console.log(JSON.stringify(LinkingModule8))

        try {
            let selectContactData = dataSource[0];
            console.log("selectContactData",JSON.stringify(selectContactData))
            await ZOHO.CRM.UI.Record.populate({
                LinkingModule8: [],
                Contract_Date: null,
                States:null,
                ProcurementTerms: null,
                AccountOrderNo: null,
                id1: null,
                Currency: null,
                DestinationPort:null,
                ShippingPort:null,
                PayMethod:null,

            })
            await ZOHO.CRM.UI.Record.populate({
                LinkingModule8: [{AccountOrderNo:null}],
            })
            let Subjects = [];
            let id1 = [];
            selectData.forEach(item => {
                if (!id1.includes(item.Parent_Id.id)) {
                    id1.push(item.Parent_Id.id)
                    Subjects.push(item.Subject)
                }
            })
            console.log('id1', id1);
            console.log('Subjects', Subjects);
            var CountryCodeid = selectContactData.CountryCodeid;
            var CountryCode = null;
            if(CountryCodeid){
                var Countryinfo = await ZOHO.CRM.API.getRecord({Entity: "States", approved: "both", RecordID:CountryCodeid});
                console.log('Countryinfo',JSON.stringify(Countryinfo));
                if(Countryinfo && Countryinfo.data && Countryinfo.data.length > 0){
                    CountryCode = {
                        id:Countryinfo.data[0].id,
                        name:Countryinfo.data[0].Name
                    }
                }
            }
            await ZOHO.CRM.UI.Record.populate({LinkingModule8: LinkingModule8,});
            console.log('selectContactData.ContractDate',selectContactData.ContractDate);


            await ZOHO.CRM.UI.Record.populate({
                LinkingModule8: LinkingModule8,
                Contract_Date:selectContactData.ContractDate,
                States:CountryCode,               //出口国家--->贸易国家
                AccountOrderNo: selectContactData.AccountOrderNo,
                Exportcontractnumberid: id1,
                Exportcontractnumber: Subjects.toString().replaceAll(",", "/"),
                Currency: selectContactData.Currency,
                DestinationPort:selectContactData.DestinationPortName,
                ShippingPort:selectContactData.ShippingPortName,
                PayMethod:selectContactData.PayMethod,
            })
            await ZOHO.CRM.UI.Popup.close().then(() => {
                this.setState({ loading: false });
            });

        } catch (e) {
            console.log(e)
        }

    };

    handleModalClose = () => {
        this.setState({ modalVisible: false })
    };

    handleOkModal = async () => {
        const { selectedContractRowKeys } = this.state
        console.log(selectedContractRowKeys)
        let crmRecordFromSql = await getCrmRecordFromSql(`select 
        Parent_Id.Subject as Subject,Product_Name.id as productid,Product_Name.Product_Name as Product,id,internalcode
        ,Quantity,Parent_Id.AccountOrderNo as AccountOrderNo ,Parent_Id.CountryCode.id as CountryCodeid,AccountprtNo,Chinesespecification,Chptrequirements_material,Chineseingredients,
        Brand,Englishname,Specification,Nuofboxesinpg,Nuofboxeinnerbox,Lengthofouterbox,Heightofouterbox,Grossweight,NumberofCartons,
        Cartonwidth,Netweight,Volume,ABQuantity,List_Price,Productname,Packagingquantityperpg,Category,Parent_Id,Parent_Id.ContractDate as ContractDate,
        Parent_Id.Terms_and_Conditions as Terms_and_Conditions,Parent_Id.Currency as Currency,Parent_Id.ShippingPort.Name as ShippingPortName,Parent_Id.DestinationPort.Name as DestinationPortName,
        Unit,Packaginunit,Parent_Id.PayMethod as PayMethod 
        from Ordered_Items where Parent_Id in (${selectedContractRowKeys}) and ABQuantity>0 order by id desc`);
        console.log(crmRecordFromSql)

        this.setState({ modalVisible: false, dataSource: crmRecordFromSql })

    };

    onContractSelectChange = (newselectedRowKeys) => {
        console.log(newselectedRowKeys)
        this.setState({ selectedContractRowKeys: newselectedRowKeys });
    };

    onSelectChange = (newselectedRowKeys) => {

        this.setState({ selectedRowKeys: newselectedRowKeys });
    };
    getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
            <div
                style={{
                    padding: 8,
                }}
                onKeyDown={(e) => e.stopPropagation()}
            >
                <Input
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{
                        marginBottom: 8,
                        display: 'block',
                    }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        搜索
                    </Button>
                    <Button
                        onClick={() => clearFilters && this.handleReset(clearFilters, dataIndex)}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        重置
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            close();
                        }}
                    >
                        关闭
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered) => (
            <SearchOutlined
                style={{
                    color: filtered ? '#1677ff' : undefined,
                }}
            />
        ),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {

            }
        },

        render: (text) =>
            text
    });
    handleSearch = (selectedKeys, confirm, dataIndex) => {
        const { searchInput, contractColumns, user } = this.state;
        searchInput[dataIndex] = selectedKeys[0];
        searchInput['Account_Name'] = window.data.Account.id
        const dataIndexArray = ['Account_Name', 'Header', 'ShipperInformationName', 'ContractDate',
            'Terms_and_Conditions', 'Currency', 'Subject', 'AccountOrderNo', 'id'];

        const typeArray = {};
        contractColumns.map(item => {
            typeArray[item.dataIndex] = item.type
        });
        getCrmByParam(dataIndexArray, typeArray, searchInput, user, "Sales_Orders").then((data) => {
            this.setState({
                contactData: data,
                searchInput: searchInput,
            })
        })
        confirm();
    };
    handleReset = (clearFilters, dataIndex) => {
        const { searchInput } = this.state;
        searchInput[dataIndex] = "";
        this.setState({
            searchInput: searchInput,
        })
        clearFilters();
    };

    handleCancel = () => {
        ZOHO.CRM.UI.Popup.close().then(() => {
            this.setState({ loading: false });
        });
    }


    render() {
        const {
            loading,
            modalVisible,
            screenHeight,
            contractColumns,
            contactData,
            selectedContractRowKeys,
            dataSource,
            column,
            selectedRowKeys
        } = this.state;

        return (
            <div>
                <Spin spinning={loading}>
                    <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
                        <div>
                            <Button disabled={loading} onClick={this.handleSave} type="primary"
                                style={{ marginRight: 10 }}>
                                保存
                            </Button>
                            <Button style={{ marginLeft: 8, marginRight: 8 }} onClick={this.handleCancel}>
                                取消
                            </Button>
                        </div>
                    </div>
                    <div>
                        <Table
                            pagination={false}
                            rowSelection={{
                                fixed: true,
                                selectedRowKeys: selectedRowKeys, // 多选表格选中行的 keys 数组
                                onChange: this.onSelectChange, // 选中行发生变化时的回调函数
                            }}
                            rowKey="id"
                            dataSource={dataSource} columns={column} />
                        <Modal
                            open={modalVisible}
                            onCancel={this.handleModalClose}
                            onOk={this.handleOkModal}
                            cancelText={"关闭"}
                            style={{ top: 0, left: 0, right: 0, bottom: 0 }}
                            width="100%"
                            okText={"确认已挑选合同"}
                            centered
                        >
                            <Table
                                rowKey="id"
                                loading={loading}
                                rowSelection={{
                                    fixed: true,
                                    selectedRowKeys: selectedContractRowKeys, // 多选表格选中行的 keys 数组
                                    onChange: this.onContractSelectChange, // 选中行发生变化时的回调函数
                                }}
                                columns={contractColumns}
                                dataSource={contactData}
                                scroll={{ x: 200 }} />
                        </Modal>
                    </div>
                </Spin>
            </div>
        );
    }
}

export default App;